/*
 * Copyright (c) 2009 Nathaniel Houghton <nathan@brainwerk.org>
 *                    Robert Kirchgessner <rkirchge@gmail.com>
 *
 * Permission to use, copy, modify, and distribute this software for
 * any purpose with or without fee is hereby granted, provided that
 * the above copyright notice and this permission notice appear in all
 * copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
 * WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
 * AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
 * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA
 * OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
 * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 * PERFORMANCE OF THIS SOFTWARE.
 *
 */

#include <stdint.h>

#include <avr/io.h>
#include <util/delay.h>

void
spi_init(void)
{
	/*
	 * PB7 - SCK, PB6 - MISO, PB5 - MOSI, PB4 - /SS.
	 */
	/* DDRB = 10110000 */
	DDRB = 0xB0;

	/* SPCR = 01011100; pg. 169 */
	SPCR = 0x5C;

	/* Enable double speed SPI */
	SPSR = 0x01;
}

void
spi_tx(const uint8_t *buf, uint8_t len)
{
	uint8_t i;

	for (i = 0; i < len; ++i) {
		SPDR = buf[i];

		while (!(SPSR & (1 << SPIF)))
			;
	}
}

void
spi_rx(uint8_t *buf, uint8_t len)
{
	uint8_t i;

	for (i = 0; i < len; ++i) {
		SPDR = 0xFF;

		while (!(SPSR & (1 << SPIF)))
			;

		buf[i] = SPDR;
	}
}
